<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>发票登记信息管理</title>
	<meta name="decorator" content="default"/>
	<script src="${ctxStatic}/typeahead/bootstrap-typeahead.js" type="text/javascript"></script>
	<script type="text/javascript">
	// Production steps of ECMA-262, Edition 5, 15.4.4.19
	// Reference: http://es5.github.com/#x15.4.4.19
	if (!Array.prototype.map) {
	    Array.prototype.map = function(callback, thisArg) {
	        var T, A, k;
	        if (this == null) {
	            throw new TypeError(" this is null or not defined");
	        }

	        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
	        var O = Object(this);

	        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
	        // 3. Let len be ToUint32(lenValue).
	        var len = O.length >>> 0;

	        // 4. If IsCallable(callback) is false, throw a TypeError exception.
	        // See: http://es5.github.com/#x9.11
	        if (typeof callback !== "function") {
	            throw new TypeError(callback + " is not a function");
	        }

	        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
	        if (thisArg) {
	            T = thisArg;
	        }

	        // 6. Let A be a new array created as if by the expression new Array(len) where Array is
	        // the standard built-in constructor with that name and len is the value of len.
	        A = new Array(len);

	        // 7. Let k be 0
	        k = 0;

	        // 8. Repeat, while k < len
	        while(k < len) {

	            var kValue, mappedValue;

	            // a. Let Pk be ToString(k).
	            //   This is implicit for LHS operands of the in operator
	            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
	            //   This step can be combined with c
	            // c. If kPresent is true, then
	            if (k in O) {

	                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
	                kValue = O[ k ];

	                // ii. Let mappedValue be the result of calling the Call internal method of callback
	                // with T as the this value and argument list containing kValue, k, and O.
	                mappedValue = callback.call(T, kValue, k, O);

	                // iii. Call the DefineOwnProperty internal method of A with arguments
	                // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
	                // and false.

	                // In browsers that support Object.defineProperty, use the following:
	                // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });

	                // For best browser support, use the following:
	                A[ k ] = mappedValue;
	            }
	            // d. Increase k by 1.
	            k++;
	        }

	        // 9. return A
	        return A;
	    };
	}

		$(document).ready(function() {
			//$("#name").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
					if('${invInfo.invType}'=='2'){
						if($('#amout').val()/$('#psnQty').val() > 50){
							showTip("您的人均消费高于50元！");
							return false;
						}
					}
					if('${invInfo.invType}'=='1'){
						if($('#amout').val() > 500){
							showTip("您的发票金额超出最高上限500元！");
							return false;
						}
					}
					if($("#transactId").val()==''){
						showTip("经办人不能为空！");
						return false;
					}
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
			
			$("#transactName").typeahead({
		        source: function (query, process) {
		            return $.ajax({
		                url: '${ctx}/sys/user/listData',
		                type: 'post',
		                data: {name: query},
		                success: function (result) {
		                	//result.list = ["Ahmedabad","Akola","Asansol","Aurangabad","Bangaluru","Baroda","Belgaon","Berhumpur","Calicut","Chennai","Chapra","Cherapunji"];
		                	if(result.list){
			                	 var resultList = result.list.map(function (item) {
			                        var aItem = { id: item.id, name: item.name };
			                        return JSON.stringify(aItem);
			                       }); 
		                    	return process(resultList);
		                	}
		                	//var resultList = "["+JSON.stringify({name:"Ahmedabad"})+"]";
		                	return process("");
		                },
		            })
		        },
	            matcher: function (obj) {
	                //var item = JSON.parse(obj);
	                //return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
	                return true;
	            },
	            sorter: function (items) {          
	                var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
	                 while (aItem = items.shift()) {
	                     var item = JSON.parse(aItem);
	                     if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
	                     else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
	                     else caseInsensitive.push(JSON.stringify(item));
	                 }
	                 return beginswith.concat(caseSensitive, caseInsensitive)
	             },
	             highlighter: function (obj) {
	                 var item = JSON.parse(obj);
	                 var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
	                 return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
	                     return '<strong style="font-weight:bold;">' + match + '</strong>'
	                 })
	             },
	             updater: function (obj) {
	                 var item = JSON.parse(obj);
	                 $('#transactId').val(item.id);
	                 $('#transactId').attr("data-name",item.name);
	                 return item.name;
	             },
		        items: 20,            // 最多显示项目数量
		        display: "name",     // 默认的对象属性名称为 name 属性
		        val: "id"           // 默认的标识属性名称为 id 属性
		  });
			
			$("#invDeptName").typeahead({
		        source: function (query, process) {
		            return $.ajax({
		                url: '${ctx}/inv/invInfo/getAllInvDeptNames',
		                type: 'post',
		                data: {invDeptName: query,invType:$("#invType").val()},
		                success: function (result) {
		                    return process(result);
		                },
		            });
		        }
		  });
			
			
			$(".btn-draft").click(function(){
				$.ajax({
	                url: '${ctx}/inv/invInfo/validator',
	                type: 'post',
	                data: {invDeptName: $("#invDeptName").val(),invDate:$("#invDate").val(),invCode:$("#invCode").val(),id:$("#id").val()
	                	,invType:$("#invType").val(),transactId:$("#transactId").val()
	                },
	                success: function (result) {
	                	if(result=='success'){
							$("#status").val('0');
							$("#inputForm").submit();
	                	}else if(result!='1'){
	                		showTip(result);
	                	}else{//提示比对信息
	                		findSimilarList('0');
	                	}
	                },
	            });
			});
			
			$(".btn-submit").click(function(){
				
				if($("#invType").val()!='5' ){
					if($("#transactId").val()=='' && $("#invType").val()!='1' ){
						showTip("经办人不能为空");
						return false;
					}
					if($("#transactId").attr('data-name')!=$("#transactName").val()){
						showTip("请选择 经办人");
						return false;
					}
				}
				$.ajax({
	                url: '${ctx}/inv/invInfo/validator',
	                type: 'post',
	                data: {invDeptName: $("#invDeptName").val(),invDate:$("#invDate").val(),invCode:$("#invCode").val(),id:$("#id").val()
	                	,invType:$("#invType").val(),transactId:$("#transactId").val()
	                	,plateNo:$("#plateNo").val()
	                },
	                success: function (result) {
	                	if(result=='success'){
							$("#status").val('1');
							$("#inputForm").submit();
	                	}else if(result!='1'){
	                		showTip(result);
	                	}else{//提示比对信息
	                	//	findSimilarList('1');
	                	}
	                },
	            });
			});
		});
		
		function findSimilarList(sta){
   		    var data = "invDeptName="+$("#invDeptName").val()+"&invDate="+$("#invDate").val()+"&invCode="+$("#invCode").val();
			
      	    var iframeUrl = "${ctx}/inv/invInfo/findSimilarList?"+data;
			 top.$.jBox.open("iframe:"+iframeUrl, "开票信息比对列表", 900,500,
				{
				buttons:{"继续保存":'ok',"取消":'cancel'}
				, submit:function(v, h, f){
	               if(v=="ok"){
	            	   $("#status").val(sta);
						$("#inputForm").submit();
	               }
	            }, loaded:function(h){
	                $(".jbox-content", top.document).css("overflow-y","hidden");
	            }, closed: function () { 
	    			
	            }
		       });
			
		}
		
		  if('0'=='${rtnCode}'){
	        	top.$.jBox.close();	
	        }
	</script>
	<style type="text/css">
	.typeahead{
	   min-width: 270px!important;
	}
	</style>
</head>
<body>
	<c:if test="${invInfo.operateFlag ne '9' }">
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/inv/invInfo/">发票查询</a></li>
		<li class="active"><a href="${ctx}/inv/invInfo/form?id=${invInfo.id}">发票登记</a></li>
	</ul>
	</c:if>
	<span class="help-inline"><font color="red">温馨提示：
		${fns:getDictLabel(invInfo.invType,'INV_TIPS','')}
		</font> </span>
	<br/>
	<form:form id="inputForm" modelAttribute="invInfo" action="${ctx}/inv/invInfo/save" method="post" class="form-horizontal">
	    
		<form:hidden path="id"/>
		<form:hidden path="operateFlag"/>
		<form:hidden path="invType"/>
	    <form:hidden path="status"/>
		<sys:message content="${message}"/>		
		<c:if test="${invInfo.invType eq '5' }">
			  <div class="control-group">
				<label class="control-label">车牌号码：</label>
				<div class="controls">
					<input type="text" name="plateNo" id="plateNo" value="${invInfo.plateNo }"  class="input-xlarge required" style="margin: 0 auto;" data-items="20" >
					
					<span class="help-inline"><font color="red">* 只录入车牌号后四位</font> </span>
				</div>
			</div>
			<%-- <div class="control-group">
				<label class="control-label">发票号码：</label>
				<div class="controls">
					<form:input path="invCode" htmlEscape="false" maxlength="100" class="input-xlarge number"/>
				</div>
			</div> --%>
			<div class="control-group">
				<label class="control-label">打车日期：</label>
				<div class="controls">
					<input name="invDate" id="invDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate required"
						value="<fmt:formatDate value="${invInfo.invDate}" pattern="yyyy-MM-dd"/>"
						onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false});"/>
					<span class="help-inline"><font color="red">*</font> </span>
				</div>
			</div>
		</c:if>
	<c:if test="${invInfo.invType ne '5' }">
		<div class="control-group">
			<label class="control-label">开票单位：</label>
			<div class="controls">
				<input type="text" name="invDeptName" id="invDeptName" value="${invInfo.invDeptName }" autocomplete="off" class="input-xlarge required" style="margin: 0 auto;" data-provide="typeahead" data-items="20" >
				
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">开票日期：</label>
			<div class="controls">
				<input name="invDate" id="invDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate required"
					value="<fmt:formatDate value="${invInfo.invDate}" pattern="yyyy-MM-dd"/>"
					onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false});"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">发票编号：</label>
			<div class="controls">
				<form:input path="invCode" htmlEscape="false" maxlength="100" class="input-xlarge number required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		</c:if>
		
		<div class="control-group">
			<label class="control-label">报销类型：</label>
			<div class="controls">
				<form:select path="claimType" class="input-medium required">
   					<form:option value=""></form:option>
					<form:options items="${fns:getDictList('INV_CLAIM_TYPE')}" itemLabel="label" itemValue="value" htmlEscape="false"/>
				</form:select>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">开票金额：</label>
			<div class="controls">
				<form:input path="amout" htmlEscape="false" maxlength="18" class="input-xlarge number required"/>
				<span class="help-inline"><font color="red">*</font> 元</span>
			</div>
		</div>
		
		<!-- 餐费 -->
		<c:if test="${invInfo.invType eq '2' }">
		<div class="control-group">
			<label class="control-label">就餐人数：</label>
			<div class="controls">
				<form:input path="psnQty"  maxlength="10" cssClass="digits required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		</c:if>
		
		<c:if test="${invInfo.invType ne '5' }">
		<div class="control-group">
			<label class="control-label">经办人：</label>
			<div class="controls">
				<input type="hidden" name="transactId" id="transactId" value="${invInfo.transactId }" data-name="${invInfo.transactName  }"/>
				<input type="text" class="input-xlarge required"  autocomplete="off" name="transactName" id="transactName" value="${invInfo.transactName }" style="margin: 0 auto;" data-provide="typeahead" data-items="30"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		</c:if>
		<div class="control-group">
			<label class="control-label">报销人：</label>
			<div class="controls">
				<form:input path="createBy.name"  maxlength="100" readonly="true"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">录入日期：</label>
			<div class="controls">
				<input name="createDate" type="text" readonly="readonly" maxlength="20" 
					value="<fmt:formatDate value="${invInfo.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">备注：</label>
			<div class="controls">
				<form:textarea path="remarks" htmlEscape="false" rows="1" maxlength="255" class="input-xxlarge "/>
			</div>
		</div>
		
		
		<c:if test="${invInfo.operateFlag ne '9' }">
			<div class="form-actions">
			<c:if test="${invInfo.status eq '0' }">
				<!-- <input id="btnSubmit" class="btn btn-primary btn-draft" type="button" value="保 存草稿"/>&nbsp; -->
				<input id="btnSubmit" class="btn btn-primary btn-submit" type="button" value="提交"/>&nbsp;
				<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
			</c:if>
			</div>
		</c:if>
		
		<c:if test="${invInfo.operateFlag eq '9' }">
			<div class="form-actions">
				<input id="btnSubmit" class="btn btn-primary btn-submit" type="button" value="提交"/>&nbsp;
			</div>
		</c:if>
		
	</form:form>
</body>
</html>